/**
 * 
 */
package uk.co.cocking.getinline2.restlet;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.restlet.Client;
import org.restlet.data.Protocol;
import org.restlet.data.Response;
import org.restlet.data.Status;

import uk.co.cocking.getinline2.exceptions.Defect;
import uk.co.cocking.getinline2.pipeline.io.CouldNotProcessRecordException;
import uk.co.cocking.getinline2.pipeline.transformers.AbstractTransformer;

public class StringRestRequester extends AbstractTransformer<String, String> {
	private final Client client = new Client(Protocol.HTTP);
	private final String baseUrl;
	
	public StringRestRequester(String baseUrl) {
		try {
			new URL(baseUrl);
		} catch (MalformedURLException e) {
			throw new Defect(baseUrl + " is not a valid URL.", e);
		}
		if (!baseUrl.endsWith("/")) {
			throw new Defect("Base URL must end with /");
		}
		this.baseUrl = baseUrl;
	}
	
	@Override
	public List<String> transform(String incomingItem)
			throws CouldNotProcessRecordException {
		try {
			return enlist(request(incomingItem));
		} catch (IOException e) {
			throw new CouldNotProcessRecordException("error servicing request "+incomingItem, e);
		}
	}
	
	private String request(String request) throws IOException, CouldNotProcessRecordException {
		Response response = client.get(baseUrl+request);
		if (!response.getStatus().equals(Status.SUCCESS_OK)) {
			throw new CouldNotProcessRecordException("Request "+request+" failed with status "+response.getStatus());
		}
		return response.getEntity().getText();
	}
}